package com.xiamaliu.demo.action;

import com.xiamaliu.spring.annotation.GPAutowired;
import com.xiamaliu.spring.annotation.GPController;
import com.xiamaliu.spring.annotation.GPRequestMapping;
import com.xiamaliu.spring.annotation.GPRequestParam;
import com.xiamaliu.demo.service.IModifyService;
import com.xiamaliu.demo.service.IQueryService;
import com.xiamaliu.spring.webmvc.servlet.GPModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@GPController
@GPRequestMapping("/web")
public class MyAction {

    @GPAutowired
    private IQueryService queryService;

    @GPAutowired
    private IModifyService modifyService;

    @GPRequestMapping("/query.json")
    public GPModelAndView query(HttpServletRequest request, HttpServletResponse response, @GPRequestParam("name") String name) {
        String query = queryService.query(name);
        return out(response, query);
    }

    @GPRequestMapping("/add.json")
    public GPModelAndView add(HttpServletRequest request, HttpServletResponse response,
                              @GPRequestParam("name") String name, @GPRequestParam("addr") String addr) throws Exception {
        try {
            String result = modifyService.add(name, addr);
            return out(response,result);
        } catch (Throwable e){
            Map<String,String> model = new HashMap<String,String>();
            model.put("detail",e.getCause().getMessage());
            model.put("stackTrace", Arrays.toString(e.getStackTrace()));
            return new GPModelAndView("500",model);
        }
    }

    @GPRequestMapping("/remove.json")
    public GPModelAndView remove(HttpServletRequest request, HttpServletResponse response,
                                 @GPRequestParam("id") Integer id) {
        String remove = modifyService.delete(id);
        return out(response, remove);
    }

    @GPRequestMapping("/edit.json")
    public GPModelAndView edit(HttpServletRequest request, HttpServletResponse response,
                               @GPRequestParam("id") Integer id,
                               @GPRequestParam("name") String name) {
        String edit = modifyService.edit(id, name);
        return out(response, edit);
    }

    private GPModelAndView out(HttpServletResponse resp, String str) {
        try {
            resp.getWriter().write(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
